
const formatDate = (strDate) => {
    if (!strDate) return undefined
    let d = new Date(strDate)
    const year = d.getFullYear();
    const month = (d.getMonth() + 1).toString().padStart(2, '0');
    const day = d.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
}
const formatDateTime = (strDate) => {
    if (!strDate) return undefined
    let d = new Date(strDate)
    const year = d.getFullYear();
    const month = (d.getMonth() + 1).toString().padStart(2, '0');
    const day = d.getDate().toString().padStart(2, '0');
    const hours = d.getHours().toString().padStart(2, '0');
    const minutes = d.getMinutes().toString().padStart(2, '0');
    const seconds = d.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const getDayByDate = (strDate, dayNumber) => {
    if (!strDate) return undefined
    const one = 24 * 60 * 60 * 1000
    let old = new Date(strDate)
    let d
    if (dayNumber) {
        d = new Date(old.getTime() - (dayNumber * one))
    } else {
        d = old
    }
    const year = d.getFullYear();
    const month = (d.getMonth() + 1).toString().padStart(2, '0');
    const day = d.getDate().toString().padStart(2, '0');
    return `${year}${month}${day}`;
}
const bde = getDayByDate(new Date(), 7)
const ede = getDayByDate(new Date())
const getDateByNumber = (value) => {
    let d = new Date()
    d.setDate(d.getDate() - value)
    return formatDate(d)
}
const saveLog = (message, domainId, type) => {
    fetch('http://localhost:8082/dataservice/data/pullDatePluginLog?message=' + message + '&domainId=' + domainId + '&type=' + type, {
        method: 'GET',
    })
}

const openFn = function (method, url) {
            
    this._method = method;
    this._url = url;
    const href = new URL(window.location.href); 
    const domainId = href.searchParams.get("domainId");
    this.addEventListener("loadend", function () {
        try {
            if(arguments[0] && arguments[0].currentTarget && arguments[0].currentTarget._url && arguments[0].currentTarget._url.indexOf('batchedDataV2') !== -1){
                const obj = JSON.parse(arguments[0].currentTarget.hookQuery)
                const dataRequest = obj.dataRequest
                // const param = dataRequest[0].requestContext.reportContext.displayType
                for (let index = 0; index < dataRequest.length; index++) {
                    const param = dataRequest[index].requestContext.reportContext.displayType
                    if(param == "simple-table"){
                        const res = this.response.slice(this.response.indexOf('{\"dataResponse'),this.response.length)
                        save(domainId,res)
                        break
                    }
                }
            }
        } catch (error) {
            console.log(error)
            saveLog(error,domainId,"error")
        }
    })
    return open.apply(this, arguments)
}
// content.js
if (window.location.href.indexOf("lookerstudio") != -1) {
    sessionStorage.setItem('javascript', `var XHR = XMLHttpRequest.prototype
        var open = XHR.open;
        var send = XHR.send;
        const saveLog = ${String(saveLog)};
        const save = (domainId,data) => {
            const headers = new Headers();
            headers.append('Content-Type', 'application/json');
            fetch('http://localhost:8082/dataservice/data/lookerStudioPlugin', {
                method: 'POST',
                headers: headers,
                body: JSON.stringify({domainId,requestBody:data})
            }).then(response => {
                    return response.json()
                }).then(data => {
                    console.log(data)
                    if(data == true){
                        saveLog("保存数据成功",domainId,"succes")
                    }else{
                        saveLog("保存数据出错",domainId,"error")
                    }
                    
                }).catch(error => {
                    console.log(error)
                    saveLog(error,domainId,"error")
                });
        }
                
        const updateObject = (obj)=>{
            if(Array.isArray(obj)){
                for (let index = 0; index < obj.length; index++) {
                    updateObject(obj[index])
                }
            }else{
                for (const key in obj) {
                    if(Array.isArray(obj[key])){
                        for (let index = 0; index < obj[key].length; index++) {
                            updateObject(obj[key][index])
                            
                        }
                    }else if(Object.prototype.toString.call(obj[key]) === '[object Object]'){
                        for (const key2 in obj[key]) {
                            updateObject(obj[key][key2])
                        }
                    }
                    if(key == 'startDate'){
                        obj[key] = ${bde}
                    }
                    if(key == 'endDate'){
                        obj[key] = ${ede}
                    }
                }
            }
        }

        XHR.send = function (postData) {
            this['hookQuery'] = postData
            if(this._url.indexOf('batchedDataV2') !== -1){
                const hq = JSON.parse(arguments[0])
                updateObject(hq)
                arguments[0] = JSON.stringify(hq)
            }
            return send.apply(this, arguments);
        }
        XHR.open = ${String(openFn)}
            `)
    const url = chrome.runtime.getURL('inject.js')
    const script = document.createElement('script')
    script.src = url
    document.body.appendChild(script)
}
if (window.location.href.indexOf("sensors") != -1) {
    sessionStorage.setItem('javascript', `var XHR = XMLHttpRequest.prototype
        var open = XHR.open;
        var send = XHR.send;

        const updateObject = (obj)=>{
            if(Array.isArray(obj)){
                for (let index = 0; index < obj.length; index++) {
                    updateObject(obj[index])
                }
            }else{
                for (const key in obj) {
                    if(Array.isArray(obj[key])){
                        for (let index = 0; index < obj[key].length; index++) {
                            updateObject(obj[key][index])
                            
                        }
                    }else if(Object.prototype.toString.call(obj[key]) === '[object Object]'){
                        for (const key2 in obj[key]) {
                            updateObject(obj[key][key2])
                        }
                    }
                    if(key == 'startDate'){
                        obj[key] = 20241101
                    }
                    if(key == 'endDate'){
                        obj[key] = 20241103
                    }
                }
            }
        }

        XHR.send = function (postData) {
            this['hookQuery'] = postData
            if(this._url.indexOf('batchedDataV2') !== -1){
                const hq = JSON.parse(arguments[0])
                updateObject(hq)
                arguments[0] = JSON.stringify(hq)
            }
            return send.apply(this, arguments);
        }
        
        XHR.open = function (method, url) {
            
            this._method = method;
            this._url = url;
            this.addEventListener("loadend", function () {
                if(arguments[0] && arguments[0].currentTarget && arguments[0].currentTarget._url && arguments[0].currentTarget._url.indexOf('batchedDataV2') !== -1){
                    const res = this.response.slice(this.response.indexOf('{\"dataResponse'),this.response.length)
                    console.log(res)
                }
            })
            return open.apply(this, arguments)
        }`)
    const url = chrome.runtime.getURL('inject.js')
    const script = document.createElement('script')
    script.src = url
    document.body.appendChild(script)
}

window.onload = async function () {
    setTimeout(async () => {
        if (window.location.href.indexOf("sensors") != -1) {
            return secondsRun()
        } else if (window.location.href.indexOf("lookerstudio") != -1) {
            // return lookerStudioRun()
        }

    }, 5000);
};